package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 这是token的拦截器
 * 交给spring托管
 * 实现接口 HandlerInterceptor
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    //注入redis
    @Autowired
    private RedisTemplate redisTemplate;

    /*//注入UserService
    @Autowired
    private UserService userService;*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取访问路径
        log.info("访问路径是" + request.getRequestURI());

        log.info("来请求的方法是" + handler);
        //2.获取请求头路径
        String token = request.getHeader("Authorization");
        //3.获取token中的数据 并判断是否存在
        if (StringUtils.isNotEmpty(token)) {
            User loginUser = getUserByToken(token);
            if (null != loginUser) {
                //登陆用户是存在的
                UserHolder.setUser(loginUser);
                return true;
            }

        }
        //4.没有token设置返回码
        response.setStatus(401);//没有认证 没有登陆
        //这里返回true则可以访问cotroller中的方法
        return false;

    }

    /**
     * 通过token获取用户信息
     * @param token
     * @return
     */
    public User getUserByToken(String token) {
        //拼接token
        String tokenKey = "TOKEN_" + token;
        //获取redis中的User数据
        String loginJsonUser = (String) redisTemplate.opsForValue().get(tokenKey);
        if (loginJsonUser == null) {
            return null;
        }
        //5.重新设置token有效期
        redisTemplate.expire(tokenKey,7, TimeUnit.DAYS);
        //获取存入redis中的id和手机号
        User user = JSON.parseObject(loginJsonUser, User.class);
        return user;
    }


}

